package org.wdcode.web.filter;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.wdcode.common.constants.StringConstants;
import org.wdcode.common.tools.Conversion;
import org.wdcode.common.util.CommonUtil;
import org.wdcode.web.params.WdWebParams;
import org.wdcode.web.util.AttributeUtil;

import java.io.IOException;

/**
 * 检测用户是否登陆
 * @author WD
 * @since JDK6
 * @version 1.0 2010-03-07
 */
public final class LoginFilter implements Filter {
	// 常量
	private final static String	FORWARD;

	// 检查为空时跳到的错误页
	private String				indexPage;
	// 跳转方式
	private String				resultType;
	// 不检查的页面
	private String[]			exceptPage;

	// 静态初始化
	static {
		FORWARD = "forward";
	}

	/**
	 * 载入过滤器到服务 读取过滤器配置参数
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		// 设置错误页
		indexPage = filterConfig.getInitParameter("indexPage");
		if (CommonUtil.isEmpty(indexPage)) {
			this.indexPage = StringConstants.BACKSLASH;
		}

		// 设置不检查的页面
		String special = filterConfig.getInitParameter("special");
		if (!CommonUtil.isEmpty(special)) {
			// 获得不检查的页面的数组形式
			exceptPage = special.split(StringConstants.COMMA);
		}

		// 设置跳转方式
		resultType = filterConfig.getInitParameter("resultType");
		if (CommonUtil.isEmpty(resultType)) {
			this.resultType = "redirect";
		}
	}

	/**
	 * 过滤
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		// 转换Request
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		// 转换Response
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		// 校验页面
		boolean find = true;
		// 获得当前页面
		String paths = httpRequest.getServletPath();
		// 有数组
		if (!CommonUtil.isEmpty(exceptPage)) {
			// 循环数组
			for (int i = 0; i < exceptPage.length; i++) {
				// 查找是相同页
				if (paths.indexOf(exceptPage[i]) >= 0) {
					// 不检查
					find = false;
					// 跳出循环
					break;
				}
			}
		}

		// 判断检查
		if (find && Conversion.toInt(AttributeUtil.get(httpRequest, WdWebParams.getSaveUser())) < 1) {
			// 判断跳转方式
			if (FORWARD.equals(resultType)) {
				// forward
				httpRequest.getRequestDispatcher(indexPage).forward(httpRequest, httpResponse);
			} else {
				// redirect
				httpResponse.sendRedirect(httpRequest.getContextPath() + indexPage);
			}
		} else {
			// 交出控制权
			filterChain.doFilter(httpRequest, httpResponse);
		}
	}

	/**
	 * 销毁实例调用
	 */
	public void destroy() {}
}
